package com.lebang.controller.buss;

import com.alibaba.fastjson.JSON;
import com.lebang.common.Login;
import com.lebang.common.Util;
import com.lebang.common.utils.MD5;
import com.lebang.component.RedisClient;
import com.lebang.component.RedisSdkClient;
import com.lebang.configuration.datasource.DataSource;
import com.lebang.entity.member.LbbMemberRecord;
import com.lebang.entity.task.TaskComments;
import com.lebang.entity.task.TaskCommentsDetail;
import com.lebang.entity.task.TaskScreenshot;
import com.lebang.example.TaskClassifyExample;
import com.lebang.example.TaskCommentsExample;
import com.lebang.example.TaskTagExample;
import com.lebang.model.enums.Booleans;
import com.lebang.model.enums.Status;
import com.lebang.model.enums.buss.RewardMode;
import com.lebang.model.enums.buss.RewardType;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.model.enums.buss.TaskStatus;
import com.lebang.service.CommentsService;
import com.lebang.service.TaskClassifyService;
import com.lebang.service.TaskScreenshotService;
import com.lebang.service.TaskTagService;
import com.lebang.service.buss.CommentDetailService;
import com.lebang.service.buss.CustomService;
import com.lebang.service.buss.MemberRecordService;
import com.lebang.service.task.TaskService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.common.UUIDUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * @Author: hwq
 * @Date: 2019/8/6 11:27
 * @Version 1.0
 */
@Controller
@RequestMapping("/sys/comments")
public class CommentsController {
    @Autowired
    private TaskService<TaskComments> taskService;
    @Autowired
    private CustomService customService;
    @Autowired
    private CommentDetailService commentDetailService;
    @Autowired
    private MemberRecordService memberRecordService;
    @Autowired
    private TaskScreenshotService taskScreenshotService;
    @Autowired
    private TaskClassifyService taskClassifyService;
    @Autowired
    private TaskTagService taskTagService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private RedisSdkClient redisSdkClient;
    @Autowired
    private CommentsService commentsService;

    @Login
    @GetMapping("/list")
    public String list(Model model) {
        model.addAttribute("Status", Status.values());
        return "/comments/list";
    }
    @Login
    @PostMapping("/data")
    @ResponseBody
    public HashMap data(Long page, Integer limit,String status){
        HashMap map = new HashMap(1);
        TaskCommentsExample example = new TaskCommentsExample();
        TaskCommentsExample.Criteria c = example.createCriteria();
        example.setOffset((page - 1) * limit);
        example.setLimit(limit);
        example.setOrderByClause("create_time desc");
        c.andHasDeletedEqualTo(0);
        if (!TextUtil.isEmpty(status)){
            Status statusOne = Status.valueOf(status);
            c.andStatusEqualTo(statusOne.getIndex());
        }
        map.put("count", commentsService.count(example));
        map.put("code", 0);
        List<TaskComments> masters = commentsService.selectAll(example);
        map.put("data", masters);
        return map;

    }


    /**
     * 新增修改保存
     **/
    @Login
    @PostMapping("/edit")
    @ResponseBody
    public JsonData edit(TaskComments data, TaskScreenshot taskScreenshot, HttpSession session) {
        taskScreenshot.setCategory(TaskCategory.Comments.name());
        taskScreenshot.setIsMultiword(0);
        data.setCreateBy(session.getAttribute("userid").toString());
        int i = 0;
        taskScreenshot.setChannel(data.getBrand());
        if(data.getStatus()==0){
            taskScreenshot.setStatus("Off");
        }
        if(data.getStatus()==1){
            taskScreenshot.setStatus("On");
        }
        if(data.getStatus()==2){
            taskScreenshot.setStatus("Wait");
        }
        if (data.getId() == null) {
            taskScreenshot.setTaskId(data.getTaskId());
            taskScreenshot.setStatus("On");
            data.setTaskScreenshot(taskScreenshot);
            i = taskService.insertTask(data);

        } else {
            data.setTaskScreenshot(taskScreenshot);
            i = taskService.updateTask(data);
        }
        if (i > 0) {
            return Callback.success("success", "操作成功", null);
        } else {
            return Callback.fail("fail", "操作失败", null);
        }
    }

    /**
     * 新增修改跳转
     **/
    @Login
    @GetMapping("/edit")
    public String edit(
            Model model, TaskComments po) {
        if (null != po.getId()) {
            po = taskService.taskInfoById(po.getId());
            TaskScreenshot taskScreenshot = taskScreenshotService.selectByTaskId(po.getTaskId());
            model.addAttribute("tags",taskScreenshotService.selectRelation(po.getTaskId()));
            model.addAttribute("taskScreenshot",Optional.ofNullable(taskScreenshot).orElse(new TaskScreenshot()));
        } else {

            po = new TaskComments();
            po.setCustomer("zy");
            po.setRedo(1);
            po.setContents("[]");
            po.setType(RewardType.Cash);
            po.setStatus(1);
            TaskScreenshot taskScreenshot = new TaskScreenshot();
            model.addAttribute("taskScreenshot",taskScreenshot);
        }
        TaskClassifyExample taskClassifyExample = new TaskClassifyExample();
        taskClassifyExample.createCriteria().andEnableEqualTo(1).andHasDeletedEqualTo("False");
        TaskTagExample taskTagExample = new TaskTagExample();
        taskTagExample.createCriteria().andEnableEqualTo(1).andHasDeletedEqualTo("False");
        model.addAttribute("taskClassifys",taskClassifyService.selectByEx(taskClassifyExample));
        model.addAttribute("taskTags",taskTagService.selectByEx(taskTagExample));
        model.addAttribute("customlist", customService.getAllCustomList());
        model.addAttribute("item", po);
        model.addAttribute("types", RewardType.values());
        return "/comments/edit";
    }

    @Login
    @GetMapping("/translation")
    public String translation(Integer id, Model model) {
        model.addAttribute("id", id);
        return "/comments/translation";
    }

    @Login
    @PostMapping("/upload")
    @ResponseBody
    public JsonData upload(MultipartFile file, HttpSession session, Integer id) throws IOException {
        try {
            String creat = session.getAttribute("userid").toString();
            List<Map<String, Object>> rows = Util.readXlsx(file.getInputStream());

            for (Iterator<Map<String, Object>> iterator = rows.iterator(); iterator.hasNext(); ) {
                Map<String, Object> next = iterator.next();
                if (next.get("msg") != null) {
                    TaskCommentsDetail detail = new TaskCommentsDetail();
                    detail.setCreateBy(creat);
                    detail.setCommentsId(id);
                    detail.setMsg(next.get("msg").toString());
                    detail.setPicture(next.get("icon") != null ? next.get("icon").toString() : "");
                    commentDetailService.insert(detail);
                }
            }
            return Callback.success("success", "导入成功", null);
        } catch (Exception e) {
            return Callback.fail("success", "导入失败", null);
        }
    }
    @Login
    @RequestMapping(value = "/checkList", method = {RequestMethod.GET})
    public String checkList(Model model) {
        model.addAttribute("taskStatus", TaskStatus.values());
        return "/comments/checkList";
    }

    @Login
    @RequestMapping(value = "/checkList", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getCheckList(String status, String stime, String etime, Integer offset, Integer limit,
                                            String customer, String title,  String phone) {
        String category = TaskCategory.Comments.name();
        return memberRecordService.pagging(category, status, stime, etime, offset, limit, title, customer, phone, 0);
    }
    @PostMapping("/reload")
    @ResponseBody
    public JsonData taskReload(String taskId) {
        TaskComments common = taskService.taskInfoByTaskId(taskId);
        if (common != null) {
            if (taskService.taskInitByTaskId(common)) {
                return Callback.success("success", "操作成功", null);
            } else {
                return Callback.fail("fail", "操作失败", null);
            }
        }
        return Callback.fail("fail", "任务不存在", null);
    }

//    @Login
    /**批量审核入口**/
    @PostMapping("/checkselectlist")
    @ResponseBody
    public JsonData checklist( String data, String tab, @RequestParam(value = "status") String status,
                               @RequestParam(value = "remark", required = false) String remark,
                               @RequestParam(value = "multiple", required = false) Integer multiple,
                               @RequestParam(value = "checkselectlist", required = false) String checkSelectList) {
        //验证
        String md5Code = MD5.getMD5Code(data + "checkselectlist");
        if (!md5Code.equals(checkSelectList)){
            return Callback.fail("fail", "操作失败", null);
        }
        List<String> list = JSON.parseArray(data, String.class);
        int i = taskService.examineAndVerify(list, tab, status, remark,1);
        if (i == -1) {
            return Callback.success("success", "操作频繁", null);
        }
        if (i > 0) {
            return Callback.success("success", "操作成功", null);
        } else {
            return Callback.fail("fail", "操作失败", null);
        }
    }


    @Login
    @RequestMapping(value = "/detail", method = {RequestMethod.POST})
    @ResponseBody
    public Object detail(@RequestParam(value = "memberid") String memberid,
                         @RequestParam(value = "taskid") String taskid, HttpServletRequest request, HttpSession session) {
        LbbMemberRecord record = memberRecordService.checkRecord(memberid, taskid, TaskCategory.Comments.name());
        if (record == null) {
            return "记录不存在！";
        }
        return record;
    }
//    @Login
    @SuppressWarnings("unlikely-arg-type")
    @RequestMapping(value = "/check", method = {RequestMethod.POST})
    @ResponseBody
    public JsonData checks(@RequestParam(value = "memberid") String memberid,
                           @RequestParam(value = "taskid") String taskid, @RequestParam(value = "status") String status,
                           @RequestParam(value = "remark", required = false) String remark, HttpServletRequest request,
                           @RequestParam(value = "multiple", required = false) Integer multiple,
                           @RequestParam(value = "check", required = false) String check, HttpSession session) {
        //验证
        String md5Code = MD5.getMD5Code(memberid + taskid + "check");
        if (!md5Code.equals(check)){
            return Callback.fail("fail", "操作失败", null);
        }
        LbbMemberRecord record = memberRecordService.checkRecord(memberid, taskid, TaskCategory.Comments.name());
        if (record == null) {
            return Callback.fail("fail", "操作失败", null);
        }
        List<String> list = new ArrayList<>(1);
        list.add(record.getId().toString());
        int i = taskService.examineAndVerify(list, "", status, remark, multiple==null?1:multiple);
        if (i > 0) {
            memberRecordService.updateMultipleById(multiple,record.getId());
            return Callback.success("success", "操作成功", null);
        } else {
            return Callback.fail("fail", "操作失败", null);
        }
    }

    /**
     * 把旧表数据补全到新表内
     * @return
     */
    @Login
    @PostMapping("/checkData")
    @ResponseBody
    public JsonData checkData(){

        String uuid = UUIDUtil.M();
        //boolean lock = redisClient.tryGetDistributedLock("COMMENTSCHECK:KEY", uuid, 10000);
        boolean lock = redisSdkClient.tryGetDistributedLock("COMMENTSCHECK:KEY", uuid, 10000);
        if (!lock) {
            return Callback.fail("fail", "勿重复操作", null);
        }

        List<TaskComments> list = taskService.taskList(null,null);
        try{
            list.forEach(s->{
                TaskScreenshot taskScreenshot = taskScreenshotService.selectByTaskId(s.getTaskId());
                if(taskScreenshot==null){
                    TaskScreenshot taskScreen = new TaskScreenshot(s);
                    taskScreenshotService.insert(taskScreen);

                }
            });
        }catch (Exception e){
            e.printStackTrace();
            return Callback.fail("fail", "操作失败", null);
        }finally {
            //redisClient.releaseDistributedLock("COMMENTSCHECK:KEY", uuid);
            redisSdkClient.releaseDistributedLock("COMMENTSCHECK:KEY", uuid);
        }

        return Callback.success("success", "操作成功", null);
    }

    @Login
    @PostMapping("/del")
    @ResponseBody
    public JsonData del(@RequestParam(value = "ids") Integer ids){
        TaskComments comments = taskService.taskInfoById(ids);
        if(comments == null){
            return Callback.fail("fail", "任务不存在", null);
        }
        taskService.deleteTask(comments);
        return Callback.success("success", "删除成功", null);
    }


    /**
     * 复制
     **/
    @Login
    @GetMapping("/copyDatao")
    public String copyDataInsert(
            Model model, TaskComments po) {

            po = taskService.taskInfoById(po.getId());
            TaskScreenshot taskScreenshot = taskScreenshotService.selectByTaskId(po.getTaskId());
            model.addAttribute("tags",taskScreenshotService.selectRelation(po.getTaskId()));
            model.addAttribute("taskScreenshot",Optional.ofNullable(taskScreenshot).orElse(new TaskScreenshot()));

        model.addAttribute("taskClassifys",taskClassifyService.selectByEx(null));
        TaskTagExample taskTagExample=new TaskTagExample();
        taskTagExample.createCriteria().andEnableEqualTo(1);
        model.addAttribute("taskTags",taskTagService.selectByEx(taskTagExample));
        model.addAttribute("customlist", customService.getAllCustomList());
        po.setId(null);
        po.setTaskId(null);
        model.addAttribute("item", po);
        model.addAttribute("types", RewardType.values());
        return "/comments/edit";
    }

    @PostMapping("/commonSwitch")
    @ResponseBody
    @Login
    public JsonData commonSwitch(TaskComments po){
        commentsService.commonSwitch(po);
        return Callback.success("success", "操作成功", null);
    }

    /**
     * 评论语查询
     * @param page
     * @param limit
     * @param commentsId
     * @return
     */
    @PostMapping("/getDetail")
    @ResponseBody
    @Login
    public Map<String, Object> getDetail(Integer page,Integer limit,Integer commentsId){
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        Integer pageSize = (page - 1) * limit;
        map.put("data",commentDetailService.getDetail(pageSize,limit,commentsId) );
        map.put("count",  commentDetailService.getDetailCount(commentsId));
        map.put("code", 0);
        return map;
    }

    /**
     * 修改评论语状态
     * @param id
     * @param status
     * @return
     */
    @Login
    @PostMapping("/update")
    @ResponseBody
    public JsonData updateDetail(Integer id,  String status) {
        Integer i=commentDetailService.updateById(id,status);
        if (i > 0) {
            return Callback.success("200", "操作成功!", null);
        } else {
            return Callback.fail("201", "操作失败!", null);
        }
    }
    /**
     * 修改评论语状态
     * @param ids
     * @return
     */
    @Login
    @PostMapping("/delDetail")
    @ResponseBody
    public JsonData delDetail(String ids) {
        boolean isSuccess =commentDetailService.delDetail(ids);
        if (isSuccess) {
            return Callback.success("200", "操作成功", "");
        }
        return Callback.fail("500", "网络异常", "");
    }
}
